import React, { useState, useEffect, useReducer } from 'react';
import { Form, Button, Row, Card, Popconfirm, message } from 'antd';
import WhiteListForm from './white-list-form';
import WhiteListTable from './white-list-table';
import WhiteListModal from './white-list-modal';
import { getWhiteList, listInitState, deleteWhite, getWhiteDetail } from 'hook/whiteList.ts';
import './index.less';

const ADDTEXT = '新建白名单';
const UPDATETEXT = '编辑白名单';

const whiteList = props => {
    const { form } = props;
    const [whiteDate, setWhiteDate] = useState(listInitState);
    const [selectedRowKeys, setRowKeys] = useState([]);
    const [modalVisible, setModalVisible] = useState(false);
    const [modalTitle, setModalTitle] = useState(ADDTEXT);
    const [tableCondition, setTableCondition] = useState({
        offset: 0,
        limit: 10,
        sort: {}
    });
    const [whiteDetail, setWhiteDetail] = useState({});
    // 显示编辑框
    const handleEditorModal = (title, id) => {
        setModalTitle(title);
        setModalVisible(true);
        if (!id) {
            setWhiteDetail({});
        } else {
            getWhiteDetail(id, setWhiteDetail, () => {
                message.error('请求错误');
            });
        }
    }

    useEffect(() => {
        handleFetchList();
    }, [tableCondition]);
    // 请求错误回调
    function errorCb(err) {
        message.error(err.msg || '请求失败');
        setWhiteDate({
            ...whiteDate,
            loading: false,
            error: err
        });
    }
    // 请求列表数据
    function handleFetchList() {
        const { getFieldsValue } = form;
        const formValue = getFieldsValue(['search_uin', 'search_remark', 'search_aegisid', 'search_operator', 'search_openid']);
        const conditions = { ...tableCondition, ...formValue };
        // 删除所有没有实际值的条件
        for (const [key, val] of Object.entries(conditions)) {
            const actualVal = typeof val === 'string' ? val.trim() : val;
            if (actualVal === undefined || actualVal === null || actualVal === '') {
                Reflect.deleteProperty(conditions, key);
            } else if (~key.indexOf('search_')) {
                Reflect.deleteProperty(conditions, key);
                conditions[key.split('search_')[1]] = actualVal;
            }
        }
        // 单独检测sort条件
        if (!conditions.sort.key) Reflect.deleteProperty(conditions, 'sort');
        getWhiteList(setWhiteDate, conditions, errorCb);
    }
    // 表格条件改变
    function handleTableChange(pagination, _, sorter) {
        const { current, pageSize } = pagination;
        const { columnKey, order } = sorter;
        setTableCondition({
            offset: (current - 1) * pageSize,
            limit: pageSize,
            sort: {
                key: columnKey,
                order
            }
        });
    }
    // 删除白名单
    function handleDelete(id): void {
        const ids = typeof id === 'string' || typeof id === 'number' ? [id] : selectedRowKeys;
        deleteWhite(setWhiteDate, ids, () => {
            message.success('删除成功');
            setRowKeys([]);
            handleFetchList();
        }, errorCb);
    }

    return (
        <div className="white-list-wrap">
            <div className="white-list-form">
                <Card title="白名单列表">
                    <WhiteListForm
                        form={form}
                        onSubmit={() => {
                            setTableCondition({ ...tableCondition, offset: 0 });
                            handleFetchList();
                        }}
                    />
                    <WhiteListModal
                        form={form}
                        title={modalTitle}
                        visible={modalVisible}
                        setStatus={setModalVisible}
                        detail={whiteDetail}
                        handleFetchList={handleFetchList}
                    />
                    <Row style={{ marginBottom: 20 }}>
                        <Button
                            type="primary"
                            icon="plus"
                            onClick={() => handleEditorModal(ADDTEXT, undefined)}
                        >
                            新建
                        </Button>
                        <Popconfirm
                            title="确认批量删除名单？"
                            onConfirm={handleDelete}
                            okText="确定"
                            cancelText="取消"
                        >
                        {
                            selectedRowKeys.length > 0 && <Button type="danger" style={{ marginLeft: 20 }}>批量删除</Button>
                        }
                        </Popconfirm>
                    </Row>
                    <WhiteListTable
                        handleEditorModal={(id) => handleEditorModal(UPDATETEXT, id)}
                        rowSelection={{ selectedRowKeys, onChange: setRowKeys }}
                        data={whiteDate}
                        onChange={handleTableChange}
                        handleDelete={handleDelete}
                    />
                </Card>
            </div>
        </div>
    );
};

export default Form.create()(whiteList);